package com.micro.play.internet.audio.book.domain.service.impl;

import com.google.common.collect.Lists;
import com.micro.play.internet.audio.book.config.prop.AppPropertiesConfig;
import com.micro.play.internet.audio.book.domain.pojo.em.WebsiteType;
import com.micro.play.internet.audio.book.domain.pojo.vo.*;
import com.micro.play.internet.audio.book.domain.service.BaseService;
import com.micro.play.internet.audio.book.domain.service.IPlayService;
import com.micro.play.internet.audio.book.extension.util.HttpUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class WtpsServiceImpl extends BaseService implements IPlayService {

    private static final String BASE_URL_FORMAT = "https://www.5tps.com%s";
    private static final String CHARSET_NAME = "GB2312";
    private static final Pattern MURL_PATTERN = Pattern.compile(";(murl\\S+)=[\"']([^\"']{0,})[\"'];url");
    private static final Pattern URL_PATTERN = Pattern.compile(";(url\\S+)=[\"']([^\"']{0,})[\"'];func");
    private static final Pattern MEDIA_PATTERN = Pattern.compile("\\{[\"']{0,}mp3[\"']{0,}\\:[\"']([^}]+)\\}");

    @Override
    public WebsiteType websiteType() {
        return WebsiteType.WTPSW;
    }

    @Autowired
    private AppPropertiesConfig config;

    @Override
    public List<SearchBookItemVO> searchBooksByKeyword(SearchBookParamVO searchBookParam) throws Throwable {
        String keyword = URLEncoder.encode(searchBookParam.getKeyword(), CHARSET_NAME);
        String url = String.format(BASE_URL_FORMAT, "/search.asp?types=1&keyword=" + keyword);
        String bodyHtml = HttpUtil.post(url, null, CHARSET_NAME);
        List<SearchBookItemVO> books = Lists.newArrayList();
        if (StringUtils.isBlank(bodyHtml)) {
            return books;
        }
        Document doc = Jsoup.parse(bodyHtml);
        Elements lis = doc.select("div.pingshu_5tps li");
        if (CollectionUtils.isEmpty(lis)) {
            return books;
        }
        for (Element li : lis) {
            Element aInfo = li.selectFirst("a");
            Element spanAuthor = li.selectFirst("span");
            SearchBookItemVO item = new SearchBookItemVO();
            item.setWebsiteType(websiteType().name());
            item.setTitle(aInfo.text() + " - " + spanAuthor.text());
            item.setUrl(String.format(BASE_URL_FORMAT, aInfo.attr("href")));
            books.add(item);
        }
        return books;
    }

    @Override
    public List<AnalyzeBookCatalogItemVO> analyzeCatalogs(AnalyzeBookCatalogParamVO analyzeBookCatalogParam) throws Throwable {
        String bodyHtml = HttpUtil.get(analyzeBookCatalogParam.getUrl(), CHARSET_NAME);
        List<AnalyzeBookCatalogItemVO> catalogs = Lists.newArrayList();
        if (StringUtils.isBlank(bodyHtml)) {
            return catalogs;
        }
        Document doc = Jsoup.parse(bodyHtml);
        Elements as = doc.select("div.bfdz li a");
        if (CollectionUtils.isEmpty(as)) {
            return catalogs;
        }
        for (Element aInfo : as) {
            AnalyzeBookCatalogItemVO item = new AnalyzeBookCatalogItemVO();
            item.setWebsiteType(websiteType().name());
            item.setTitle(analyzeBookCatalogParam.getTitle() + " - " + aInfo.text());
            item.setUrl(String.format(BASE_URL_FORMAT, aInfo.attr("href")));
            catalogs.add(item);
        }
        return catalogs;
    }

    @Override
    public AnalyzePlayUrlItemVO analyzePlayUrl(AnalyzePlayUrlParamVO analyzePlayUrlParam) throws Throwable {
        String bodyHtml = HttpUtil.get(analyzePlayUrlParam.getUrl(), CHARSET_NAME);
        Document doc = Jsoup.parse(bodyHtml);
        Element iframe = doc.selectFirst("iframe#play");
        String src = String.format(BASE_URL_FORMAT, iframe.attr("src"));
        // 获取播放器页面
        String originPlayHtml = HttpUtil.get(src, CHARSET_NAME);
        String playHtml = StringUtils.removePattern(originPlayHtml, "\\s");
        // 返回结果
        AnalyzePlayUrlItemVO item = new AnalyzePlayUrlItemVO();
        item.setTitle(analyzePlayUrlParam.getTitle());
        item.setWebsiteType(websiteType().name());
        // 查询url并替换值
        Matcher murlMatcher = MURL_PATTERN.matcher(playHtml);
        Matcher urlMatcher = URL_PATTERN.matcher(playHtml);
        if (!urlMatcher.find() || !murlMatcher.find()) {
            return item;
        }
        String[] searchList = new String[]{"+" + urlMatcher.group(1) + "+", "+" + murlMatcher.group(1) + "+"};
        String[] replacementList = new String[]{urlMatcher.group(2), murlMatcher.group(2)};
        playHtml = StringUtils.replaceEach(playHtml, searchList, replacementList);
        // 查询最终url
        Matcher mediaMatcher = MEDIA_PATTERN.matcher(playHtml);
        if (!mediaMatcher.find()) {
            return item;
        }
        String mediaSrc = mediaMatcher.group(1);
        mediaSrc = StringUtils.removePattern(mediaSrc, "[\"']");
        item.setUrl(mediaSrc);
        return item;
    }

}
